package com.satan.config.security;

import cn.hutool.core.util.ObjectUtil;
import com.satan.entity.SysUser;
import com.satan.exception.AccountStatusException;
import com.satan.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName MyUserDetailsService
 * @Description TODO
 * @date 2023/10/3 20:49
 * @Version 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MyUserDetailsService implements UserDetailsService {
    private final SysUserService sysUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录的用户为:{}",username);
        SysUser sysUser = sysUserService.getUserByName(username);
        if (ObjectUtil.isEmpty(sysUser)) {
            throw new UsernameNotFoundException("用户名或者密码错误!");
        } else if ("1".equals(sysUser.getStatus())) {
            throw new AccountStatusException("该用户账号被封禁,具体请联系管理员!");
        }
        //获取用户权限包括角色权限和菜单权限
        List<GrantedAuthority> authorities = getUserAuthority(sysUser.getId());
//        log.info("获取到的用户权限:{}", authorities);

        return new User(username, sysUser.getPassword(), authorities);
    }
    public List<GrantedAuthority> getUserAuthority(Long userId){
        String authority=sysUserService.getUserAuthority(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
